package io.terminus.lego.shinda.web.oauth2.resource

import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer
import org.springframework.security.oauth2.provider.token.TokenStore

/**
 * 授权资源配置
 * @author wangmeng
 * @date 2018/4/12
 */
@Configuration
@EnableResourceServer
class ResourceServerConfig @Autowired constructor(val tokenStore: TokenStore) : ResourceServerConfigurerAdapter() {

    private val SPARKLR_RESOURCE_ID = "shinda-maru"

    override fun configure(resources: ResourceServerSecurityConfigurer) {
        resources.resourceId(SPARKLR_RESOURCE_ID).stateless(false).tokenStore(tokenStore)
    }

    override fun configure(http: HttpSecurity) {
        // @formatter:off
        http
                // Since we want the protected resources to be accessible in the UI as well we need
                // session creation to be allowed (it's disabled by default in 2.0.6)
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
                .and()
                .requestMatchers().antMatchers("/api/oauth/**")
                .and()
                .authorizeRequests()
                .antMatchers("/api/oauth/me").access("#oauth2.hasScope('public_profile')")
        super.configure(http)
    }
}